//
//  MBBannerView.m
//  MemberBusiness-ios
//
//  Created by cherry pu on 2018/5/4.
//  Copyright © 2018年 zhangXin. All rights reserved.
//

#import "MBBannerView.h"
#import "MBPageControl.h"
#import "MBBannerButton.h"
#import "MBBannerView.h"

@interface MBBannerView ()<UIScrollViewDelegate>
@property (nonatomic,strong)MBPageControl* pagecontrol;
@property (nonatomic,strong)UIScrollView* scrollView;
@property (nonatomic,strong)UIView* contentView;
@property (nonatomic,strong)NSTimer* scrollTimer;
@property (nonatomic,assign)int scrollTopicFlag;
@property (nonatomic,strong)UIImage* defaultImage;
@property (nonatomic,assign)CGFloat lastOffset;

@end

@implementation MBBannerView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        UIScrollView* scrollView = [[UIScrollView alloc]init];
        scrollView.userInteractionEnabled = YES;
        scrollView.directionalLockEnabled = YES;
        self.scrollView = scrollView;
        scrollView.delegate = self;
        scrollView.pagingEnabled = YES;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:scrollView];
        
        [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self).insets(UIEdgeInsetsZero);
        }];
        
        UIView* contentView = [[UIView alloc]init];
        self.contentView = contentView;
        [scrollView addSubview:contentView];
        
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(scrollView).insets(UIEdgeInsetsZero);
        }];
        
        MBPageControl * pageControl = [[MBPageControl alloc] init];
        pageControl.currentPageIndicatorTintColor = COLOR_MAIN;
        pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        [self addSubview:pageControl];
        self.pagecontrol = pageControl;
        
        [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.scrollView).with.offset(-[UIView lf_sizeFromIphone6:5]);
            make.centerX.equalTo(self.scrollView);
        }];
        
        
    }
    return self;
}

-(void)setCurImageArray:(NSArray *)curImageArray
{
    _curImageArray = curImageArray;
    
    [self setUpOtherControl];
}

/**
 *  控件创建
 */
-(void)setUpOtherControl
{
    if (self.curImageArray.count == 0) {
        return;
    }
    
    
    NSMutableArray * tempImageArray = [[NSMutableArray alloc]init];
    [tempImageArray addObject:[self.curImageArray lastObject]];
    for (id obj in self.curImageArray) {
        [tempImageArray addObject:obj];
    }
    [tempImageArray addObject:[self.curImageArray objectAtIndex:0]];
    
    for (int i=0; i<tempImageArray.count; i++) {
        MBBannerButton* curButton = [[MBBannerButton alloc]init];
        curButton.imageView.contentMode = UIViewContentModeScaleAspectFill;
        curButton.imageView.layer.masksToBounds = YES;
        if (i == tempImageArray.count-1) {
            curButton.tag = 0;
        }else if (i == 0) {
            curButton.tag = tempImageArray.count-3;
        }else {
            curButton.tag = i-1;
        }
        [curButton addTarget:self action:@selector(handleBannerVButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        if ([tempImageArray[i] isKindOfClass:[NSString class]]) {
            curButton.imageUrl = tempImageArray[i];
            NSString* imageUrl = tempImageArray[i];
            if (![imageUrl containsString:@"http"]) {
                imageUrl = [NSString stringWithFormat:@"%@%@",BASE_IMAGE_URL,tempImageArray[i]];
            }
            
            UIImage* image = [[MBCacheService sharedInstance]fetchBannerImageWithUrl:tempImageArray[i]];
            if (image) {
                [curButton setImage:image forState:UIControlStateNormal];
            }else {
                [curButton sd_setImageWithURL:[NSURL URLWithString:imageUrl] forState:UIControlStateNormal placeholderImage:self.defaultImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    if (image) {
                        [[MBCacheService sharedInstance]cacheBannerImageWithUrl:tempImageArray[i] andImage:image];
                    }
                    [[SDImageCache sharedImageCache]clearMemory];
                }];
            }
        }else {
            [curButton setImage:[UIImage createImageWithColor:COLOR_BG] forState:UIControlStateNormal];
        }
        
        curButton.layer.masksToBounds = YES;
        [self.contentView addSubview:curButton];
        
        [curButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.height.mas_equalTo(self.height);
            make.top.equalTo(self.contentView);
            make.left.equalTo(self.contentView).with.offset(SCREEN_WIDTH*i);
        }];
        
        if (i == tempImageArray.count-1) {
            [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.bottom.equalTo(curButton);
            }];
        }
        
    }
    
    [self.scrollView setContentSize:CGSizeMake(self.frame.size.width*[tempImageArray count], self.frame.size.height)];
    [self.scrollView setContentOffset:CGPointMake(self.frame.size.width, 0)];
    
    self.pagecontrol.numberOfPages = self.curImageArray.count;
    
    if (self.scrollTimer) {
        [self.scrollTimer invalidate];
        self.scrollTimer = nil;
    }
    
    if ([tempImageArray count]>3) {
        self.scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTopic) userInfo:nil repeats:YES];
        self.scrollView.scrollEnabled = YES;
    }else {
        self.scrollView.scrollEnabled = NO;
    }
    
    self.lastOffset = self.size.width;
    
}

-(void)scrollTopic{
    [self.scrollView setContentOffset:CGPointMake(self.frame.size.width*self.scrollTopicFlag, 0) animated:YES];
    
    if (self.scrollTopicFlag >= (int)([self.curImageArray count]+2)) {
        self.scrollTopicFlag = 1;
    }else {
        self.scrollTopicFlag++;
    }
}


#pragma mark - UIScrollView Delegate
//滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat Width=self.frame.size.width;
    
    if (scrollView.contentOffset.x <= 0) {
        [self.scrollView setContentOffset:CGPointMake(Width*([self.curImageArray count]), 0) animated:NO];
    }else if (scrollView.contentOffset.x >= Width*([self.curImageArray count]+1)) {
        [self.scrollView setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
    }
    
    int currentPage = (scrollView.contentOffset.x/self.frame.size.width)-1;
    self.pagecontrol.currentPage = currentPage;
    if (currentPage + 2 == 2) {
        self.scrollTopicFlag = 2;
    }else if (currentPage + 2 == self.curImageArray.count+1) {
        self.scrollTopicFlag = (int)self.curImageArray.count+2;
    }else {
        self.scrollTopicFlag = currentPage+1;
    }
    
}


-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    self.scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTopic) userInfo:nil repeats:YES];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (self.scrollTimer) {
        [self.scrollTimer invalidate];
        self.scrollTimer = nil;
    }
    
}

#pragma mark - lazy load

- (UIImage *)defaultImage {
    if (_defaultImage == nil) {
        _defaultImage = [UIImage imageNamed:@"home_banner_back"];
    }
    return _defaultImage;
}

#pragma mark - 点击
- (void)handleBannerVButtonEvent:(MBBannerButton *)button {
    self.clickImageUrl = button.imageUrl;
}

@end
